package Executor;

import Command.SetCommand;
import HttpServer.FunctionTable;
import HttpServer.HttpServerClient;

import java.util.concurrent.*;

public class DbThreadExecutor {

    private static ThreadPoolExecutor threadPool;
    private static ScheduledExecutorService Scheduledservice;
    public static void init(){
        System.out.println("线程池初始化");
        Scheduledservice = Executors.newSingleThreadScheduledExecutor();
        threadPool = new ThreadPoolExecutor(12,12,30,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(128),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }



    public static String submit(String path,String key,String value ) throws ExecutionException, InterruptedException {

        return (String) threadPool.submit(()->(FunctionTable.map.get(path).apply(key,value) ) ).get();
    }

    public static void submitProducer(String path,String key,String value,String expireTime )  {

        threadPool.submit(()->{
            System.out.println("Producer...");
                HttpServerClient.queue.push(new SetCommand(path,key,value,expireTime));
        });
    }

    public static void submitConsumer() {
        threadPool.submit(()->{

            while (true){

                SetCommand setCommand =  HttpServerClient.queue.pop();
                if(setCommand!=null){
                   FunctionTable.map.get(setCommand.getPath()).apply(setCommand,null) ;
                   HttpServerClient.aofCreater.aofWrite(setCommand);

                }
            }

        });
    }


    public static void scheduleAtFixedRate(  Runnable runnable,long initialDelay,long period){
        Scheduledservice.scheduleAtFixedRate( runnable,initialDelay,period, TimeUnit.SECONDS);
    }


    public static void shutdown(){
        threadPool.shutdown();
        Scheduledservice.shutdown();

    }





}
